package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: fxx
 * @Date: 2021/1/13 21:40
 */

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;
    //方法之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过JWT拦截器");
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")){
            final String token = header.substring(7);
            try {
                Claims claims = jwtUtil.parseJWT(token);
                if (claims != null){
                    if ("admin".equals(claims.get("roles"))){
                        request.setAttribute("admin_claims", claims);
                    }
                    if ("user".equals(claims.get("roles"))){
                        request.setAttribute("user_claims", claims);
                    }
                }
            }catch (Exception e){
                throw new RuntimeException("令牌不正确");
            }
        }
        return true;
    }
}
